import { CommonModule } from '@angular/common';
import { ChangeDetectorRef, Component, DestroyRef, inject, OnInit } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { finalize } from 'rxjs';

import { RequestParams } from '@app/core/domain/request-params';
import { UserSession, UserSessionService } from '@app/core/services/http/login-log/user-session.service';
import { PageSearchParams } from '@app/pages/system-manage/dept/dept.component';
import { AntTableComponent, AntTableConfig, SortFile } from '@app/shared/components/ant-table/ant-table.component';
import { CardTableWrapComponent } from '@app/shared/components/card-table-wrap/card-table-wrap.component';
import { PageHeaderComponent, PageHeaderType } from '@app/shared/components/page-header/page-header.component';
import { WaterMarkComponent } from '@app/shared/components/water-mark/water-mark.component';
import { NzBadgeModule } from 'ng-zorro-antd/badge';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzGridModule } from 'ng-zorro-antd/grid';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzMessageModule, NzMessageService } from 'ng-zorro-antd/message';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { NzSwitchModule } from 'ng-zorro-antd/switch';
import { NzTableQueryParams } from 'ng-zorro-antd/table';

@Component({
  selector: 'app-login-log',
  standalone: true,
  imports: [
    NzMessageModule,
    PageHeaderComponent,
    FormsModule,
    NzFormModule,
    NzGridModule,
    NzInputModule,
    NzButtonModule,
    NzIconModule,
    CardTableWrapComponent,
    AntTableComponent,
    CommonModule,
    NzPopconfirmModule,
    NzBadgeModule,
    NzSpaceModule,
    NzCardModule,
    WaterMarkComponent,
    NzSwitchModule
  ],
  templateUrl: './login-log.component.html',
  styleUrl: './login-log.component.less'
})
export class LoginLogComponent implements OnInit {
  pageSearchParam: Partial<PageSearchParams> = {};
  tableConfig!: AntTableConfig;
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '登录日志',
    breadcrumb: ['首页', '系统日志', '登录日志']
  };
  isCollapse: boolean = true;
  loginLogs: UserSession[] = [];
  checkedCashArray: NzSafeAny[] = [];
  private readonly destroyRef = inject(DestroyRef);
  private readonly messageService: NzMessageService = inject(NzMessageService);
  private readonly userSessionService: UserSessionService = inject(UserSessionService);
  private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef);

  private initTable(): void {
    this.tableConfig = {
      headers: [
        {
          title: '用户名',
          width: 130,
          field: 'username',
          show: true,
          showSort: true
        },
        {
          title: 'Ip地址',
          width: 130,
          field: 'ip',
          show: true,
          showSort: true
        },
        {
          title: '登录时间',
          width: 130,
          field: 'logintime',
          show: true,
          showSort: true
        },
        {
          title: '登出时间',
          width: 130,
          field: 'logouttime',
          show: true,
          showSort: true
        }
      ],
      total: 0,
      showCheckbox: true,
      loading: false,
      pageSize: 10,
      pageIndex: 1
    };
  }

  selectedChecked(e: NzSafeAny): void {
    this.checkedCashArray = [...e];
  }

  resetForm(): void {
    this.pageSearchParam = {};
    this.search();
  }

  toggleCollapse(): void {
    this.isCollapse = !this.isCollapse;
  }

  reloadTable(): void {
    this.messageService.info('已经刷新了');
    this.getLoginLogs();
  }

  tableChangeDectction(): void {
    this.loginLogs = [...this.loginLogs];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  appendRequestParams(): RequestParams {
    const filter: Partial<UserSession> = {};
    let requestParams: RequestParams = {
      '@relationships': 'UserInfo',
      current: this.tableConfig.pageIndex,
      pageSize: this.tableConfig.pageSize,
      '@filter': '',
      ...filter
    };

    if (this.pageSearchParam.Name) {
      requestParams['@filter'] += `contains(UserName,${this.pageSearchParam.Name})`;
    }

    return requestParams;
  }

  getLoginLogs(e?: NzTableQueryParams): void {
    if (e) {
      this.tableConfig.pageIndex = e?.pageIndex;
    }
    this.checkedCashArray = [...this.checkedCashArray];
    this.tableConfig.loading = true;
    let requestParams: RequestParams = this.appendRequestParams();

    this.userSessionService
      .getEntityPageList(requestParams)
      .pipe(
        finalize(() => {
          this.tableLoading(false);
        }),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(students => {
        const { records, total } = students;
        this.loginLogs = records;
        this.tableConfig.total = total;
      });
  }

  changeSort(e: SortFile): void {
    //e.fileName , e.sortDir
  }

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  search(): void {
    this.tableConfig.pageIndex = 1;
    this.getLoginLogs();
  }

  ngOnInit(): void {
    this.initTable();
  }
}
